/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package courseScheduler;

import java.sql.*;

/**
 *
 * @author Lucy
 */
public class Room {
    private String building;
    private int room;
    private int id;

    private PreparedStatement getRoomStatement;
    private PreparedStatement setRoomStatement;
    private PreparedStatement insertRoomStatement;

    private Connection conn;

    Room (String newBuilding, int newRoom){
        building = newBuilding;
        room = newRoom;
    }

    Room (Connection newConn, int newID) throws SQLException{
        PrepareGetStmnt();
        id = newID;
        getRoomStatement.setInt(1, newID);
        ResultSet rs = getRoomStatement.executeQuery();
        if (rs.first()){
            int count = 0;
            do {
                count ++;
            } while (rs.next());
            rs.first();
            if (count < 2){
                building = rs.getString(1);
                room = rs.getInt(2);
            }
            else {
                javax.swing.JOptionPane.showMessageDialog(null, "Multiple entries found");
            }
        }
        else {
            System.out.println("no entries found");
        }
    }

    private void PrepareGetStmnt() throws SQLException{
        getRoomStatement = conn.prepareStatement("SELECT building,room FROM room WHERE id = ?;");
    }

    private void PrepareSetStmnt() throws SQLException {
        setRoomStatement = conn.prepareStatement("UPDATE room building = \"" + building + "\",room = " + room +" WHERE id = ?;");
    }

    private void PrepareInsertStmnt() throws SQLException{
        insertRoomStatement = conn.prepareStatement
        (
            "INSERT INTO room (building,room) VALUES (\"" + building + "\"," + room + ");"
        );
    }

    public static int GetID(Connection newConn, String newBuilding, String newRoom) throws SQLException{
        Statement stmnt = newConn.createStatement();
        ResultSet rs = stmnt.executeQuery("SELECT id FROM room WHERE building LIKE \"" + newBuilding + "\" AND room = " + newRoom +";");
        rs.first();
        return rs.getInt(1);
    }
    
    public final void setBuilding(String newBuilding){
        building = newBuilding;
    }
    
    public String getBuilding(){
        return building;
    }
    
    public final void setRoom(int newRoom){
        room = newRoom;
    }
    
    public int getRoom (){
        return room;
    }
    
    public final void setID(int newID){
        id = newID;
    }
    
    public int getID(){
        return id;
    }

    public final void setConnection(java.sql.Connection newConn) throws java.sql.SQLException{
        conn = newConn;
        PrepareGetStmnt();
        PrepareSetStmnt();
        PrepareInsertStmnt();
    }
}
